<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    let data = [
      { id: 2, pid: 1 },
      { id: 5, pid: 2 },
      { id: 3, pid: 1 },
      { id: 1, pid: 0 },
      { id: 4, pid: 2 },
      { id: 6, pid: 3 }
    ]
    // 定义一个方法使上面数组变成树状结构
    // list 是要处理的数组 ,pid是上一级的父id
    function tranListToTreeData(list, pid) {
      let arr = []
      list.forEach((item) => {
        if (item.pid === pid) {
          // 继续调用判断是否有下一级
          const children = tranListToTreeData(list, item.id)
          if (children.length) item.children = children
          arr.push(item)
        }
      })
      return arr
    }
    let res = tranListToTreeData(data, 0)
    console.log(res)
  </script>
</html>
